<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <div class="filter-wrapper">
      <NewPageFilter
        ref="pageFilter"
        v-model:query="filterInfo.query.queryMap"
        :query-more-json="true"
        :filter-list="filterInfo.searchList"
        :filter-btn="filterInfo.searchBtn"
        :clear-type="clearType"
        :slip-select-request="slipSelectRequest"
      >
        <template v-slot:filter-operateTime>
          <el-date-picker
            v-model="operateTime"
            format="YYYY-MM"
            value-format="YYYY-MM"
            type="monthrange"
            range-separator="至"
            start-placeholder="操作时间开始日期"
            end-placeholder="操作时间结束日期"
            :default-time="[new Date(2000, 1), new Date(2000, 2)]"
            @change="timeChange"
          ></el-date-picker>
        </template>
      </NewPageFilter>
    </div>

    <div class="filter-wrapper">
      <NewPageFilter :filter-btn="filterInfo.btnList">
        <template v-slot:filter-print>
          <el-button
            v-if="$permission('consumePariPassuDetails:print')"
            @click="print"
            >打印</el-button
          >
        </template>
        <template v-slot:filter-excel>
          <el-button
            v-if="$permission('consumePariPassuDetails:excel')"
            @click="exportExcel"
            >导出excel</el-button
          >
        </template>
      </NewPageFilter>
      <div class="display-flex">
        <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <TableContainer
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="tableInfo.api"
      :summary="true"
      :summary-field-list="tableInfo.summaryFieldList"
      :tab-index="true"
      :check-box="false"
      :query="filterInfo.query"
      :field-list="tableInfo.fieldList"
      :rowKey="'uuid'"
      @sortChange="sortChange"
      @handleEvent="handleEvent"
    >
    </TableContainer>

    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      :field-list="tableInfo.fieldList"
      v-model:form-data="advancedSearchInfo.data"
      @callback="advancedSearchCallback"
    />
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
  </div>
</template>

<script setup name="consumePariPassuDetails">
import {
  excelConsumePariPassuDetailsByDept,
  printConsumePariPassuDetailsByDept,
  getConsumePariPassuDetailsByDeptPage,
  getConsumePariPassuDetailsByDeptPageSum,
} from '@/api/dataQuery.js'
import moment from 'moment'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
const { proxy } = getCurrentInstance()
const props = defineProps(['query'])

const filterInfo = ref({
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      deptAuth: {
        asTbName: 'depot_stock_affair',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
      operateTime: {
        queryType: 'BETWEEN',
        value:
          moment(new Date(new Date().getTime() - 3600 * 1000 * 24 * 90)).format(
            'YYYY-MM'
          ) +
          ',' +
          moment(new Date()).format('YYYY-MM'),
      },
      isConsignBusiness: {
        queryType: 'IN',
        value: 0,
      },
      isEstimationStockBusiness: {
        queryType: 'IN',
        value: 0,
      },
    },
    queryParams: {
      useFiscalPeriod: 0,
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      value: 'print',
      type: 'slot',
    },
    {
      value: 'excel',
      type: 'slot',
    },
  ],
})
const operateTime = ref([
  moment(new Date(new Date().getTime() - 3600 * 1000 * 24 * 90)).format(
    'YYYY-MM'
  ),
  moment(new Date()).format('YYYY-MM'),
])
const clearType = ref(true)
const slipSelectRequest = ref(true)
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  summaryFieldList: [
    {
      value: 'currentPeriodAmount',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      value: 'earlyPeriodAmount',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      value: 'correspondingPeriodAmount',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      value: 'growthRate',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      value: 'earlyGrowthRate',
      formatter: proxy.$fn.qtyFormatter,
    },
  ],
  fieldList: [],
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const allSummaryData = ref({
  data: [],
  fieldList: [
    {
      label: '同比增长率',
      value: 'growthRate',
    },
    {
      label: '前期同比增长率',
      value: 'earlyGrowthRate',
    },
  ],
})
watch(
  () => filterInfo.value.query.queryMap?.fiscalPeriodName?.value,
  (val) => {
    if (val) {
      filterInfo.value.query.queryMap.operateTime.value = ''
      operateTime.value = null
    }
  }
)
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  let arr = [
    // {
    //   asTbName: "depot_stock_affair",
    //   columnName: "depot_id",
    //   queryType: "IN",
    //   queryCategory: "AND",
    //   value: "deptAuth",
    // },
    // {
    //   asTbName: "depot_stock_affair",
    //   columnName: "depot_id",
    //   queryType: "IN",
    //   queryCategory: "AND",
    //   value: "depotAuth",
    // },
  ]
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
async function getList() {
  tableInfo.value.refresh = Math.random()
  getSummary()
}

function search() {
  console.log(
    filterInfo.value.query.queryMap.operateTime.value,
    filterInfo.value.query.queryMap,
    filterInfo.value.query.queryMap.operateTime.value &&
      filterInfo.value.query.queryMap.fiscalPeriodName.value,
    '11111'
  )
  if (
    filterInfo.value.query.queryMap.operateTime.value &&
    filterInfo.value.query.queryMap.fiscalPeriodName.value
  ) {
    proxy.$message.warning('操作时间和会计区间只能选择其中一个！')
    return
  }
  if (filterInfo.value.query.queryMap.operateTime.value) {
    let startTime =
      typeof operateTime.value[0] === 'string'
        ? new Date(operateTime.value[0])
        : operateTime.value[0]
    let endTime =
      typeof operateTime.value[1] === 'string'
        ? new Date(operateTime.value[1])
        : operateTime.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('操作时间间隔不能超过一年！')
    } else {
      filterInfo.value.query.queryParams.useFiscalPeriod = 0
      advancedSearchInfo.value.data = {}
      filterInfo.value.query.queryDtoList = []
      tableInfo.value.initCurpage = Math.random()
      tableInfo.value.refresh = Math.random()
      getSummary()
      return
    }
  } else {
    if (!filterInfo.value.query.queryMap.fiscalPeriodName.value) {
      proxy.$message.warning('在操作时间和会计区间中请选择一个')
    }
  }
  if (filterInfo.value.query.queryMap.fiscalPeriodName.value) {
    filterInfo.value.query.queryParams.useFiscalPeriod = 1
    advancedSearchInfo.value.data = {}
    filterInfo.value.query.queryDtoList = []
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
    getSummary()
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  operateTime.value = [
    new Date(new Date().getTime() - 3600 * 1000 * 24 * 90),
    new Date(),
  ]
  filterInfo.value.query.queryMap.operateTime.value =
    moment(new Date(new Date().getTime() - 3600 * 1000 * 24 * 90)).format(
      'YYYY-MM-DD HH:mm:ss'
    ) +
    ',' +
    moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'ConsumePariPassuDetailsByDept-com.slip.spd.entity.vo.dataquery.ConsumePariPassuDetailsVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )

      tableInfo.value.fieldList = tableFieldInfo.fieldList
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      let queryIn = proxy.$route.params.query
      if (queryIn) {
        filterInfo.value.query.queryMap = {
          ...filterInfo.value.query.queryMap,
          ...queryIn.queryMap,
        }
        if (queryIn.queryMap.operateTime) {
          operateTime.value = queryIn.queryMap.operateTime.value.split(',')
        }
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })

      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getConsumePariPassuDetailsByDeptPage
      getList()
    }
  })
}

function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.toString()
    getList()
  }
}

function exportExcel() {
  if (
    filterInfo.value.query.queryMap.operateTime.value &&
    filterInfo.value.query.queryMap.fiscalPeriodName.value
  ) {
    proxy.$message.warning('操作时间和会计区间只能选择其中一个！')
    return
  }
  if (filterInfo.value.query.queryMap.operateTime.value) {
    let startTime =
      typeof operateTime.value[0] === 'string'
        ? new Date(operateTime.value[0])
        : operateTime.value[0]
    let endTime =
      typeof operateTime.value[1] === 'string'
        ? new Date(operateTime.value[1])
        : operateTime.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('操作时间间隔不能超过一年！')
    } else {
      filterInfo.value.query.queryParams.useFiscalPeriod = 0
      excelConsumePariPassuDetailsByDept(
        proxy.$fn.delEmptyAttribute(filterInfo.value.query)
      ).then((resp) => {
        if (resp) {
          proxy.$fn.parseExcel(resp)
        }
      })
      return
    }
  } else {
    if (!filterInfo.value.query.queryMap.fiscalPeriodName.value) {
      proxy.$message.warning('在操作时间和会计区间中请选择一个')
    }
  }
  if (filterInfo.value.query.queryMap.fiscalPeriodName.value) {
    filterInfo.value.query.queryParams.useFiscalPeriod = 1
    excelConsumePariPassuDetailsByDept(
      proxy.$fn.delEmptyAttribute(filterInfo.value.query)
    ).then((resp) => {
      if (resp) {
        proxy.$fn.parseExcel(resp)
      }
    })
  }
}

function timeChange(val) {
  if (val && val.length) {
    proxy.$refs.pageFilter.clearFiscalPeriod()
    proxy.$nextTick(() => {
      filterInfo.value.query.queryMap.operateTime.value = String(val)
      filterInfo.value.query.queryMap.fiscalPeriodName.value = null
    })
  } else {
    filterInfo.value.query.queryMap.operateTime.value = ''
  }
}
//打印
function print() {
  if (
    filterInfo.value.query.queryMap.operateTime.value &&
    filterInfo.value.query.queryMap.fiscalPeriodName.value
  ) {
    proxy.$message.warning('操作时间和会计区间只能选择其中一个！')
    return
  }
  if (filterInfo.value.query.queryMap.operateTime.value) {
    let startTime =
      typeof operateTime.value[0] === 'string'
        ? new Date(operateTime.value[0])
        : operateTime.value[0]
    let endTime =
      typeof operateTime.value[1] === 'string'
        ? new Date(operateTime.value[1])
        : operateTime.value[1]
    if (endTime.getTime() - startTime.getTime() > 3600 * 1000 * 24 * 365) {
      proxy.$message.warning('操作时间间隔不能超过一年！')
    } else {
      filterInfo.value.query.queryParams.useFiscalPeriod = 0
      fatchTemplateByCode({
        resourceCode: 'consumePariPassuDetails:print',
        isDefault: 1,
      }).then((res) => {
        if (res && res.success) {
          let temp = proxy.$fn.getPrintTemp(res.data[0])
          getPrintData(temp)
        }
      })
      return
    }
  } else {
    if (!filterInfo.value.query.queryMap.fiscalPeriodName.value) {
      proxy.$message.warning('在操作时间和会计区间中请选择一个')
    }
  }
  if (filterInfo.value.query.queryMap.fiscalPeriodName.value) {
    filterInfo.value.query.queryParams.useFiscalPeriod = 1
    fatchTemplateByCode({
      resourceCode: 'consumePariPassuDetails:print',
      isDefault: 1,
    }).then((res) => {
      if (res && res.success) {
        let temp = proxy.$fn.getPrintTemp(res.data[0])
        getPrintData(temp)
      }
    })
  }
}
function getPrintData(temp) {
  let params = {
    customizeDto: filterInfo.value.query,
  }
  printConsumePariPassuDetailsByDept(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function getSummary() {
  let params = {}
  if (
    filterInfo.value.query.queryDtoList &&
    filterInfo.value.query.queryDtoList.length
  ) {
    params = proxy.$fn.deepClone(filterInfo.value.query)
    params.queryMap = {}
  } else {
    params = filterInfo.value.query
  }
  getConsumePariPassuDetailsByDeptPageSum(params).then((res) => {
    if (res && res.success) {
      if (res.data) {
        allSummaryData.value.data = [
          { growthRate: res.data.growthRate },
          { earlyGrowthRate: res.data.earlyGrowthRate },
        ]
        tableInfo.value.summaryFieldList.forEach((element) => {
          element['summaryNum'] = res.data[element.value]
        })
      } else {
        allSummaryData.value.data = []
      }
    }
  })
}
let obj = {
  fiscalPeriodName: {
    label: '会计期间',
    value: 'fiscalPeriodName',
    asValue: 'fiscalPeriodName',
    componentType: 'select-fiscal-period',
    query: {
      fiscalType: 1,
    }, //1 = 物资 2 = 资产
    checkBox: true,
    highlightRow: true,
    show: false,
    hidden: true,
  },
  operateTime: {
    label: '操作时间',
    value: 'operateTime',
    slot: true,
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
</script>

<style scoped></style>
